<?php

namespace App\Morefun\Quiz;

use Illuminate\Http\Request;
use Illuminate\Container\Container;
use Illuminate\Support\Arr;

class PaperService
{
    public function format(Request $request)
    {
        $referer = $request->headers->get('referer');
        $query = parse_url($referer, PHP_URL_QUERY);
        $tenant_id = '';
        if ($query) {
            $args = [];
            parse_str($query, $args);
            $tenant_id = Arr::get($args, 'TenantID','');
        }
        $uid = $request->json('uid', '');
        $uniqueid = md5(strtolower($tenant_id.$uid));
        return [
            'activity_id' => $request->json('activity_id'),
            'uid' => $uniqueid,
            'user_agent' => $this->formatUserAgents($request),
            'start_at' => $request->json('start_time'),
        ];
    }

    public function formatUserAgents(Request $request)
    {
        $agent = Container::getInstance()->make('agent');

        return [
            'ip' => $request->ip(),
            'platform' => $agent->platform(),
            'browser' => $agent->browser(),
            'device' => $agent->device(),
            'source' => $agent->match('/.*?(MicroMessenger\/([0-9.]+))\s*/') ? 'wechat' : 'PC',
        ];
    }
}
